package edu.ccut.saturn.studio.dialog.transformdialog;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.dialogs.TitleAreaDialog;
import org.eclipse.jface.viewers.CellEditor;
import org.eclipse.jface.viewers.ComboBoxCellEditor;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.TextCellEditor;
import org.eclipse.jface.window.Window;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.MouseTrackAdapter;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.dialogs.ElementListSelectionDialog;

import edu.ccut.saturn.studio.Activator;
import edu.ccut.saturn.studio.Images;
import edu.ccut.saturn.studio.core.util.eclipse.Messages;
import edu.ccut.saturn.studio.core.util.eclipse.SaturnSWTUtils;
import edu.ccut.saturn.studio.dialog.SelectionCandidate;
import edu.ccut.saturn.studio.dialog.TableViewerContentProvider;
import edu.ccut.saturn.studio.logic.model.saturn.SaturnContent;
import edu.ccut.saturn.studio.logic.model.saturn.SaturnTransformNode;

public class SaturnTransformDialog extends TitleAreaDialog {

	private Text idText;
	private Combo typeComb;
	private Shell shell;

	private TableViewer tableViewer;

	private Table table;

	private Text transformNameText, transformValueKeyText,
			transformDescriptionText;

	private Label browse;

	private Button addButton, editButton, deleteButton, upButton, downButton;

	private List<SaturnContent> contentList = new ArrayList<SaturnContent>();

	private SaturnTransformNode saturnTransformNode;

	public SaturnTransformDialog(Shell parentShell,
			SaturnTransformNode saturnTransformNode) {
		super(parentShell);
		this.shell = parentShell;
		this.saturnTransformNode = saturnTransformNode;
	}

	protected Control createContents(Composite parent) {
		Control contents = super.createContents(parent);
		setMessage(SelectionCandidate.SETTING_ATTRIBUTE
				+ saturnTransformNode.getName());
		return contents;
	}

	@Override
	protected Control createDialogArea(Composite parent) {

		setTitleImage(Activator.getImage(Images.SATURN_ICONS_MAXNAME));

		Composite area = (Composite) super.createDialogArea(parent);
		Composite container = new Composite(area, SWT.NONE);
		final GridLayout gridLayout = new GridLayout();
		gridLayout.numColumns = 3;
		container.setLayout(gridLayout);
		final GridData gd_container = new GridData(SWT.FILL, SWT.FILL, true,
				true);
		gd_container.widthHint = 532;
		container.setLayoutData(gd_container);

		setContentList(saturnTransformNode.getContents());

		final Label idLabel = new Label(container, SWT.NONE);
		final GridData gd_idLabel = new GridData(SWT.DEFAULT, 19);
		idLabel.setLayoutData(gd_idLabel);
		idLabel.setText("ID");

		idText = new Text(container, SWT.READ_ONLY | SWT.BORDER);
		idText.setTextLimit(150);
		final GridData gd_idText = new GridData(SWT.FILL, SWT.CENTER, true, false);
		gd_idText.horizontalIndent = 10;
		idText.setLayoutData(gd_idText);
		idText.setText(saturnTransformNode.getId().trim());
		new Label(container, SWT.NONE);

		final Label nameLabel = new Label(container, SWT.NONE);
		final GridData gd_nameLabel = new GridData();
		gd_nameLabel.heightHint = 19;
		nameLabel.setLayoutData(gd_nameLabel);
		nameLabel.setText(Messages.getString("SaturnTransformDialog.name")); //$NON-NLS-1$

		transformNameText = new Text(container, SWT.BORDER);
		transformNameText.setTextLimit(50);
		final GridData gd_transformNameText = new GridData(SWT.FILL, SWT.FILL,
				true, false, 2, 1);
		gd_transformNameText.horizontalIndent = 10;
		transformNameText.setLayoutData(gd_transformNameText);
		transformNameText.setText(saturnTransformNode.getName());

		final Label valueKeylabel = new Label(container, SWT.NONE);
		final GridData gd_valueKeylabel = new GridData(SWT.LEFT, SWT.TOP,
				false, false);
		gd_valueKeylabel.verticalIndent = 3;
		valueKeylabel.setLayoutData(gd_valueKeylabel);
		valueKeylabel.setText(Messages.getString("SaturnTransformDialog.expression"));  //$NON-NLS-1$

		transformValueKeyText = new Text(container, SWT.BORDER);
		transformValueKeyText.setTextLimit(150);
		final GridData gd_transformValueKeyText = new GridData(SWT.FILL,
				SWT.CENTER, true, false);
		gd_transformValueKeyText.horizontalIndent = 10;
		transformValueKeyText.setLayoutData(gd_transformValueKeyText);
		transformValueKeyText.setText(saturnTransformNode.getValueKey());

		browse = new Label(container, SWT.NONE);
		browse.addMouseTrackListener(new MouseTrackAdapter() {
			public void mouseEnter(final MouseEvent e) {
				browse
						.setImage(Activator.getImage(Images.AMPLIFY_MINUS)); //$NON-NLS-1$
			}

			public void mouseExit(final MouseEvent e) {
				browse.setImage(Activator.getImage(Images.AMPLIFY_PLUS)); //$NON-NLS-1$
			}
		});
//		browse.addMouseListener(new MouseAdapter() {
//			public void mouseDown(final MouseEvent e) {
//
//				browse.setImage(SWTResourceManager.getImage(
//						SaturnTransformDialog.class, Messages
//								.getString("SaturnTransformDialog.8"))); //$NON-NLS-1$
//
//				ElementListSelectionDialog dialog1 = new ElementListSelectionDialog(
//						shell, new SaturnSWTUtils.SaturnLabelDefaultProvider());
//				dialog1.setTitle(Messages.getString("SaturnTransformDialog.9")); //$NON-NLS-1$
//				dialog1.setElements(saturnTransformNode.getContentValueKeys());
//				if (dialog1.open() == Window.OK) {
//					transformValueKeyText.setText((String) dialog1
//							.getFirstResult());
//					browse.setImage(SWTResourceManager.getImage(
//							SaturnTransformDialog.class, Messages
//									.getString("SaturnTransformDialog.10"))); //$NON-NLS-1$
//				}
//
//			}
//		}		);
		
		
		browse.addMouseListener(new MouseAdapter() {
		public void mouseDown(final MouseEvent e) {

			browse.setImage(Activator.getImage(Images.AMPLIFY_MINUS)); //$NON-NLS-1$

			ElementListSelectionDialog dialog1 = new ElementListSelectionDialog(
					shell, new SaturnSWTUtils.SaturnLabelDefaultProvider());
			dialog1.setTitle(Messages.getString("SaturnTransformDialog.ChooseKeyValue")); //$NON-NLS-1$
			dialog1.setElements(saturnTransformNode.getContentValueKeys());
			if (dialog1.open() == Window.OK) {
				transformValueKeyText.setText((String) dialog1
						.getFirstResult());
				browse.setImage(Activator.getImage(Images.AMPLIFY_MINUS)); //$NON-NLS-1$
			}

		}
	}		);
		browse.setImage(Activator.getImage(Images.AMPLIFY_PLUS)); //$NON-NLS-1$
		final GridData gd_browse = new GridData();
		browse.setLayoutData(gd_browse);

		final Label descriptionLabel = new Label(container, SWT.NONE);
		final GridData gd_descriptionLabel = new GridData(SWT.LEFT, SWT.TOP,
				false, false);
		gd_descriptionLabel.verticalIndent = 5;
		descriptionLabel.setLayoutData(gd_descriptionLabel);
		descriptionLabel.setText(Messages.getString("SaturnTransformDialog.description"));  //$NON-NLS-1$

		transformDescriptionText = new Text(container, SWT.BORDER | SWT.WRAP
				| SWT.V_SCROLL);
		transformDescriptionText.setTextLimit(200);
		final GridData gd_transformDescriptionText = new GridData(SWT.FILL,
				SWT.FILL, false, false, 2, 1);
		gd_transformDescriptionText.verticalIndent = 5;
		gd_transformDescriptionText.horizontalIndent = 10;
		gd_transformDescriptionText.heightHint = 44;
		transformDescriptionText.setLayoutData(gd_transformDescriptionText);
		transformDescriptionText.setText(saturnTransformNode.getDescription());

		final Label typeLabel = new Label(container, SWT.NONE);
		typeLabel.setText(Messages.getString("SaturnTransformDialog.type")); //$NON-NLS-1$

		typeComb = new Combo(container, SWT.NONE);
		typeComb.setTextLimit(50);
		final GridData gd_typeComb = new GridData(SWT.FILL, SWT.CENTER, true,
				false, 2, 1);
		gd_typeComb.horizontalIndent = 10;
		typeComb.setLayoutData(gd_typeComb);
		typeComb.setItems(SelectionCandidate.transformTypes);
		typeComb.setText(saturnTransformNode.getType());

		final Group group = new Group(container, SWT.NONE);
		group.setLayout(new FormLayout());
		final GridData gd_group = new GridData(SWT.FILL, SWT.FILL, false, true,
				3, 1);
		gd_group.horizontalIndent = 3;
		gd_group.heightHint = 182;
		gd_group.widthHint = 489;
		group.setLayoutData(gd_group);
		group.setText(Messages.getString("SaturnTransformDialog.TypeDefine"));  //$NON-NLS-1$

		tableViewer = new TableViewer(group, SWT.MULTI | SWT.BORDER
				| SWT.FULL_SELECTION | SWT.V_SCROLL);

		// 内容器与标签器的设置
		tableViewer.setContentProvider(new TableViewerContentProvider());
		tableViewer.setLabelProvider(new SaturnTransformLabelProvider());

		table = tableViewer.getTable();
		final FormData fd_table_1 = new FormData();
		fd_table_1.bottom = new FormAttachment(0, 172);
		fd_table_1.top = new FormAttachment(0, 20);
		fd_table_1.right = new FormAttachment(0, 456);
		fd_table_1.left = new FormAttachment(0, 5);
		table.setLayoutData(fd_table_1);
		table.setLinesVisible(true);
		table.setHeaderVisible(true);

		// 让表格可以直接编辑
		tableViewer.setColumnProperties(new String[] { "id", "type",
				"contentValueKey" });

		CellEditor[] cellEditor = new CellEditor[3];
		cellEditor[0] = null;
		cellEditor[1] = new ComboBoxCellEditor(tableViewer.getTable(),
				SelectionCandidate.transformClassTypes, SWT.READ_ONLY);
		cellEditor[2] = new TextCellEditor(tableViewer.getTable());

		tableViewer.setCellEditors(cellEditor);
		tableViewer
				.setCellModifier(new MyCellModifierSaturnContent(tableViewer));

		final TableColumn newColumnTableColumn_0 = new TableColumn(table,
				SWT.NONE);
		newColumnTableColumn_0.setWidth(146);
		newColumnTableColumn_0.setText(Messages.getString("SaturnTransformDialog.ParaID")); //$NON-NLS-1$

		final TableColumn newColumnTableColumn_1 = new TableColumn(table,
				SWT.NONE);
		newColumnTableColumn_1.setWidth(147);
		newColumnTableColumn_1.setText(Messages.getString("SaturnTransformDialog.Type")); //$NON-NLS-1$

		final TableColumn newColumnTableColumn_2 = new TableColumn(table,
				SWT.NONE);
		newColumnTableColumn_2.setWidth(147);
		newColumnTableColumn_2.setText(Messages.getString("SaturnTransformDialog.Expression")); //$NON-NLS-1$
		tableViewer.setInput(contentList);

		addButton = new Button(group, SWT.NONE);
		final FormData fd_addButton = new FormData();
		fd_addButton.left = new FormAttachment(100, -52);
		fd_addButton.top = new FormAttachment(0, 10);
		fd_addButton.right = new FormAttachment(100, -12);
		addButton.setLayoutData(fd_addButton);
		addButton.setText(SelectionCandidate.ADD_BUTTON);
		addButton.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent e) {
				openAddDialog();
			}
		});

		editButton = new Button(group, SWT.NONE);
		final FormData fd_editButton = new FormData();
		fd_editButton.top = new FormAttachment(addButton, 5, SWT.BOTTOM);
		fd_editButton.right = new FormAttachment(addButton, 0, SWT.RIGHT);
		fd_editButton.left = new FormAttachment(addButton, 0, SWT.LEFT);
		editButton.setLayoutData(fd_editButton);
		editButton.setText(SelectionCandidate.EDIT_BUTTON);
		editButton.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent e) {
				IStructuredSelection selection = (IStructuredSelection) tableViewer
						.getSelection();
				if (selection.isEmpty()) {
					MessageDialog.openInformation(null,
							SelectionCandidate.HINT,
							SelectionCandidate.CHOOSE_A_RECORD);
				} else {
					openEditorDialog();
				}
			}
		});

		deleteButton = new Button(group, SWT.NONE);
		final FormData fd_deleteButton = new FormData();
		fd_deleteButton.right = new FormAttachment(editButton, 0, SWT.RIGHT);
		fd_deleteButton.left = new FormAttachment(editButton, 0, SWT.LEFT);
		fd_deleteButton.top = new FormAttachment(editButton, 5, SWT.BOTTOM);
		deleteButton.setLayoutData(fd_deleteButton);
		deleteButton.setText(SelectionCandidate.DELETE_BUTTON);
		deleteButton.addSelectionListener(new SelectionAdapter() {
			@SuppressWarnings("unchecked")
			public void widgetSelected(SelectionEvent event) {
				IStructuredSelection selection = (IStructuredSelection) tableViewer
						.getSelection();
				SaturnContent saturncontent = (SaturnContent) selection
						.getFirstElement();
				if (selection.isEmpty()) {
					MessageDialog.openInformation(null,
							SelectionCandidate.HINT,
							SelectionCandidate.CHOOSE_A_RECORD);
				} else {
					List<SaturnContent> parameterVolist = (List<SaturnContent>) tableViewer
							.getInput();
					parameterVolist.remove(saturncontent);// 删除容器中的数据
					reorder(parameterVolist);
					tableViewer.remove(saturncontent);// 删除表格中的数据
					tableViewer.setInput(parameterVolist);
				}
			}
		});

		upButton = new Button(group, SWT.NONE);
		final FormData fd_upButton = new FormData();
		fd_upButton.top = new FormAttachment(deleteButton, 5, SWT.BOTTOM);
		fd_upButton.right = new FormAttachment(deleteButton, 0, SWT.RIGHT);
		fd_upButton.left = new FormAttachment(deleteButton, 0, SWT.LEFT);
		upButton.setLayoutData(fd_upButton);
		upButton.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(final SelectionEvent e) {
				IStructuredSelection selection = (IStructuredSelection) tableViewer
						.getSelection();
				if (selection.isEmpty()) {
					MessageDialog.openInformation(null,
							SelectionCandidate.HINT,
							SelectionCandidate.CHOOSE_A_RECORD);
				} else {
					if (tableViewer.getTable() != null) {
						int i = table.getSelectionIndex();
						if (i > 0) {
							SaturnContent tps = contentList.get(i);
							List<?> parameterVolist = (List<?>) tableViewer
									.getInput();
							parameterVolist.remove(tps);
							contentList.get(i - 1).setId(
									""
											+ (Integer.valueOf(contentList.get(
													i - 1).getId()) + 1));
							tableViewer.remove(tps);
							tps.setId("" + (Integer.valueOf(tps.getId()) - 1));
							contentList.add(i - 1, tps);
							tableViewer.setInput(parameterVolist);
							table.setSelection(i - 1);
						}
					}
				}

			}

		});
		upButton.setText(SelectionCandidate.UP_BUTTON);

		downButton = new Button(group, SWT.NONE);
		final FormData fd_downButton = new FormData();
		fd_downButton.top = new FormAttachment(upButton, 5, SWT.BOTTOM);
		fd_downButton.right = new FormAttachment(upButton, 0, SWT.RIGHT);
		fd_downButton.left = new FormAttachment(upButton, 0, SWT.LEFT);
		downButton.setLayoutData(fd_downButton);
		downButton.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(final SelectionEvent e) {

				IStructuredSelection selection = (IStructuredSelection) tableViewer
						.getSelection();
				if (selection.isEmpty()) {
					MessageDialog.openInformation(null,
							SelectionCandidate.HINT,
							SelectionCandidate.CHOOSE_A_RECORD);
				} else {
					if (table.getItemCount() > 1) {

						if (tableViewer.getTable() != null) {
							int i = table.getSelectionIndex();
							if (i < tableViewer.getTable().getItemCount() - 1) {
								SaturnContent tps = contentList.get(i + 1);
								List<?> parameterVolist = (List<?>) tableViewer
										.getInput();
								parameterVolist.remove(tps);
								contentList.get(i).setId(
										""
												+ (Integer.valueOf(contentList
														.get(i).getId()) + 1));
								tableViewer.remove(tps);
								tps.setId(""
										+ (Integer.valueOf(tps.getId()) - 1));
								contentList.add(i, tps);
								tableViewer.setInput(parameterVolist);

							}
						}
					}
				}
			}
		});

		downButton.setText(SelectionCandidate.DOWN_BUTTON);

		/**
		 * 名称不可为空
		 * 
		 */
		transformNameText.addModifyListener(new ModifyListener() {
			public void modifyText(final ModifyEvent e) {
				if ("".equals(transformNameText.getText().trim())) {
					setErrorMessage(Messages.getString("SaturnTransformDialog.NameLimit")); //$NON-NLS-1$
					getButton(IDialogConstants.OK_ID).setEnabled(false);
				} else {
					setErrorMessage(null);
					getButton(IDialogConstants.OK_ID).setEnabled(true);
				}
			}
		});

		return area;
	}

	@Override
	protected void buttonPressed(int buttonId) {
		if (contentList == null) {
			return;
		}
		if (buttonId == IDialogConstants.OK_ID) {
			saturnTransformNode.setValueKey(transformValueKeyText.getText()
					.trim());
			saturnTransformNode.setName(transformNameText.getText().trim());
			saturnTransformNode.setDescription(transformDescriptionText
					.getText().trim());
			saturnTransformNode.setContents(contentList);
			saturnTransformNode.setType(typeComb.getText());
		}

		super.buttonPressed(buttonId);
	}

	public List<SaturnContent> getContentList() {
		return contentList;
	}

	public void setContentList(List<SaturnContent> contentList) {
		List<SaturnContent> fadeContentList = new ArrayList<SaturnContent>();
		for (SaturnContent saturnContent : contentList) {
			SaturnContent content = new SaturnContent(saturnContent);
			fadeContentList.add(content);
		}
		this.contentList = fadeContentList;
	}

	@Override
	protected Point getInitialSize() {
		return new Point(554, 452);
	}

	private void openAddDialog() {
		SaturnTransformDialogForAdd addDialog = new SaturnTransformDialogForAdd(
				shell, contentList, saturnTransformNode);
		if (addDialog.open() == IDialogConstants.OK_ID) {
			addDialog.addList(contentList);
			tableViewer.setInput(contentList);
		}
	}

	private void openEditorDialog() {

		SaturnTransformDialogForEdit editDialog = new SaturnTransformDialogForEdit(
				shell, saturnTransformNode);

		SaturnContent saturncontent = (SaturnContent) contentList.get(tableViewer
				.getTable().getSelectionIndex());
		editDialog.setIdstr(saturncontent.getId());
		editDialog.setTypestr(saturncontent.getType());
		editDialog.setTypevaluekeystr(saturncontent.getContentValueKey());
		editDialog.open();
		if (editDialog.i == 1) {
			saturncontent.setId(editDialog.getIdstr());
			saturncontent.setType(editDialog.getTypestr());
			saturncontent.setContentValueKey(editDialog.getTypevaluekeystr());

			tableViewer.setInput(contentList);
		}
	}

	private void reorder(List<SaturnContent> contentes) {

		if (contentes != null) {
			Collections.sort(contentes);
			for (int i = 0; i < contentes.size(); i++) {
				contentes.get(i).setId("" + (i + 1));
			}
		}
	}

	protected int getShellStyle() {
		return SWT.RESIZE | SWT.CLOSE;
	}

	protected void configureShell(Shell newShell) {
		super.configureShell(newShell);
		newShell.setText(SelectionCandidate.ATTRIBUTE_SETTING);
		newShell.setImage(Activator.getImage(Images.SATURN_ICONS_SMALLNAME));
	}

	@Override
	protected void createButtonsForButtonBar(Composite parent) {
		super.createButtonsForButtonBar(parent);
		getButton(IDialogConstants.OK_ID).setEnabled(true);
	}
}
